package it.java.giw.dataextraction.aleph.wrapper.comingsoon;

import it.java.giw.dataextraction.aleph.helper.CSVHelper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomAttr;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class CoomingsoonWrapperWorker implements Runnable {

	private LinkedBlockingQueue<String> datasetFiles;
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;
	private HashMap<String, String> attr2xpath;

	private List<String[]> results;
	private CSVHelper helper;

	/*EXAMPLES
    System.out.println(page.getTitleText());
    System.out.println(page.getHtmlElementById("footer"));
    //System.out.println(page.getAnchorByName("anchor_name"));

    //get list of all divs
    System.out.println(page.getByXPath("//div"));
    final String pageAsXml = page.asXml();
    System.out.println(pageAsXml.contains("<body class=\"composite\">"));
    final String pageAsText = page.asText();
    System.out.println(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
	 */

	public CoomingsoonWrapperWorker(LinkedBlockingQueue<String> datasetFiles, CountDownLatch startSignal, CountDownLatch doneSignal, CSVHelper helper) {
		this.datasetFiles = datasetFiles;
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
		this.results = new ArrayList<String[]>();
		this.attr2xpath = new HashMap<String,String>();
		this.helper = helper;
		initMap();
	}

	private void initMap() {
		/* xpaths di mymovies */
		attr2xpath = new HashMap<String, String>();
		attr2xpath.put("title", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/div[@class='cs-component__contentsheader cinema profile']/div[@class='cs-component__contentsheader-titlerow']/h1/text()");
		attr2xpath.put("directors", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/section[@class='cs-components__section-contentsbox']/div[@class='product-profile-box']/div[@class='product-profile-box-middlerow']/div[@class='product-profile-box-middlerow-left']/ul[@class='product-profile-box-middlerow-list']/li/strong[text()='REGIA']/../a/text()");
		attr2xpath.put("genre", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/section[@class='cs-components__section-contentsbox']/div[@class='product-profile-box']/div[@class='product-profile-box-middlerow']/div[@class='product-profile-box-middlerow-left']/ul[@class='product-profile-box-middlerow-list']/li/strong[text()='GENERE']/../span/text()");
		attr2xpath.put("year", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/section[@class='cs-components__section-contentsbox']/div[@class='product-profile-box']/div[@class='product-profile-box-middlerow']/div[@class='product-profile-box-middlerow-left']/ul[@class='product-profile-box-middlerow-list']/li/strong[text()='ANNO']/../text()");
		attr2xpath.put("rating", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/section[@class='cs-components__section-contentsbox']/div[@class='product-profile-box']/div[@class='product-profile-box-toprow']/div[@class='product-profile-box-toprow-right']/div[@class='product-profile-box-toprow-rating']/div[@class='vociFilm isHide']/div[@class='cont-rating cont-score']/div[@id='star-rating']/p/span[1]/text()");
		attr2xpath.put("actors", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/section[@class='cs-components__section-contentsbox']/div[@class='product-profile-box']/div[@class='product-profile-box-middlerow']/div[@class='product-profile-box-middlerow-left']/ul[@class='product-profile-box-middlerow-list']/li/strong[text()='ATTORI']/../a/text()");
		attr2xpath.put("poster", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/section[@class='cs-components__section-contentsbox']/div[@class='product-profile-box']/div[@class='product-profile-box-toprow']/div[@class='product-profile-box-toprow-left']/img[@id='product-profile-box-image-poster']/@src");
		attr2xpath.put("trailerLink", "//body/section[@class='cs-section']/div[@class='cs-section__content-container container_12']/div[@class='cs-section__content-main cs-pages__film-profile grid_8']/div[@class='cs-section__content-main-inside white-background']/div[@class='cs-component__contentsheader cinema profile']/nav[@class='cs-component__contentsheader-menurow']/ul[@class='cs-component__contentsheader-menurow-nav']/li[@class='item2']/a/@href");

		/* fine xpaths mymovies */

	}

	public void run() {
		try {
			startSignal.await();
			while(!datasetFiles.isEmpty()){
				/* create webClient and set options to get only HTML */
				final WebClient webClient = new WebClient();
				webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
				webClient.getOptions().setCssEnabled(false);
				webClient.getOptions().setJavaScriptEnabled(false);
				webClient.getOptions().setAppletEnabled(false);

				HtmlPage page;
				try {
					String[] info = new String[10];
					for(int i = 0; i<info.length; i++)
							info[i] = "";
					String filename = datasetFiles.poll();
					page = webClient.getPage("file:///home/roberto/workspace/AlephDataExtractor/download/"+filename);
					info[0] = filename;
					System.out.println(filename);
					if(!page.getByXPath(attr2xpath.get("title")).isEmpty())
						info[1] = page.getByXPath(attr2xpath.get("title")).get(0).toString();
					
					for(Object s : page.getByXPath(attr2xpath.get("directors")))
						info[2] += s+";";
					
					for(Object s : page.getByXPath(attr2xpath.get("genre")))
						info[3] += s.toString()+",";
					
					if(!page.getByXPath(attr2xpath.get("year")).isEmpty());{
						String year = page.getByXPath(attr2xpath.get("year")).get(0).toString();
						info[4] = year.substring(year.length()-4, year.length());
					}
					
					if(!page.getByXPath(attr2xpath.get("rating")).isEmpty()){
						String rating = page.getByXPath(attr2xpath.get("rating")).get(0).toString();
						info[5] = rating+"/10";
					}
					
					for(Object s : page.getByXPath(attr2xpath.get("actors")))
						info[6] += s.toString()+",";
					
					if(!page.getByXPath(attr2xpath.get("poster")).isEmpty()){
						DomAttr poster = (DomAttr) page.getByXPath(attr2xpath.get("poster")).get(0);
						info[7] = poster.getValue();
					}
					
					if(!page.getByXPath(attr2xpath.get("trailerLink")).isEmpty()){
						DomAttr trailerLink = (DomAttr) page.getByXPath(attr2xpath.get("trailerLink")).get(0);
						info[8] = trailerLink.getValue();
					}
					
					results.add(info);

				} catch (FailingHttpStatusCodeException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				catch (IndexOutOfBoundsException e){
					System.out.println("Errore parsing");
				}
			}
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			doneSignal.countDown();
		}finally{
			try {
				for(String[] row : results)
					helper.writeCSV(row,"Collection ComingSoon.csv");
			} catch (Exception e) {
				e.printStackTrace();
			}
			doneSignal.countDown();
		}
	}
}
